from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib

#返回结果格式
def resultData():
    data = {"websiteType": 0, "titleName": "", "titleHref": "", "source": "", "label": "", "volume": "", "summary": "","detailId": '', "publishTime": "", "category": "", "quote": "", "abstract": "", "doi": "", "downLoad": "","keyword": [], "author": [], }
    return data

def formData(response):
    allData = []
    soup = BeautifulSoup(response.text, "html5lib")
    allNum = soup.select(".results-total")[0].text.replace(",", "").strip()
    div = soup.select(".productListing > div")
    for li in div:
        tempData = resultData()
        try:
            tempData["titleName"] = li.select(".articleTitle")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = "https://www.thieme-connect.de" + li.select(".articleTitle")[0]["href"].strip()
        except:
            pass
        try:
            tempData["source"] = li.select(".articleSource")[0].text.strip()
        except:
            pass
        try:
            tempData["author"] = [d.strip() for d in li.select(".authors")[0].text.strip().split("; ")]
        except:
            pass
        allData.append(tempData)
    return allData, allNum

def getData(keyword):
    headers = {'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','Referer': 'https://www.thieme-connect.de/products/all/home.html','Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', }
    params = (('query', keyword), ('radius', 'fulltext'), ('option', 'AND'), ('clearSavedProfileSearch', 'true'),)
    response = requests.get('https://www.thieme-connect.de/products/all/search', headers=headers, params=params)
    allData, allNum = formData(response)
    return allData, allNum

def index(request):
    data = json.loads(request.POST.get('data', '1'))
    allData, allNum = getData(data["values"][0])
    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")







